package com.wang.project.consumer.payment;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.project.constant.PaymentEnum;
import com.wang.project.constant.UserConstant;
import com.wang.project.email.EmailPayMessageHandle;
import com.wang.project.model.entity.Payment;
import com.wang.project.model.entity.User;
import com.wang.project.service.PaymentService;
import com.wang.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * consumerGroup 配置暂时没什么用，但是必须要配置
 */
@Service
@Slf4j
@RocketMQMessageListener(
        topic = "payment_refreshKey_result_topic",
        consumerGroup = "payment-refreshKey-group"
)
public class paymentFreshKeyResultConsumer implements RocketMQListener<Map<String, String>> {

    @Resource
    private UserService userService;

    @Resource
    private PaymentService paymentService;

    @Resource
    private EmailPayMessageHandle emailPayMessageHandle;


    /**
     * 更改用户的支付态，不用刷洗ak sk
     *
     * @param params
     */
    @Override
    public void onMessage(Map<String, String> params) {
        log.info("paymentFreshKeyConsumer success Map params: " + JSONUtil.toJsonStr(params));
        //更改用户的支付态
        /**
         * todo 暂时不知道支付成功的调用中有什么参数，猜测应该有支付单号
         */
        String paymentOrder = params.get("outTradeNo");
        QueryWrapper<Payment> paymentQueryWrapper = new QueryWrapper<>();
        paymentQueryWrapper.eq("paymentOrder", paymentOrder);
        Payment payment = paymentService.getOne(paymentQueryWrapper);
        payment.setPayStatus(PaymentEnum.Paid.getCode());
        boolean updatePayStatus = paymentService.save(payment);
        if (!updatePayStatus) {
            log.info("paymentFreshKeyConsumer onMessage 更新支付状态失败");
        }
        Long userId = payment.getUserId();
        User user = userService.getById(userId);
        if (user.getIsVip() == UserConstant.ISVIP) {
            log.info("用户已经是会员，请勿重复消费");
            return;
        }
        user.setIsVip(UserConstant.NOVIP);
        boolean update = userService.updateById(user);
        if (!update) {
            log.info("paymentFreshKeyConsumer onMessage 更改用户支付态失败");
            return ;
        }
        log.info("用户：{} 完成支付流程 end...", userId);

        //邮件通知
        String orderCode = payment.getPaymentOrder();
        emailPayMessageHandle.sendPayMessage(orderCode,userId);
    }
}
